<?php
namespace app\common\controller;

use app\common\controller\Api;
use think\Db;

class Pic extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];


    public function createPoster($config = array(), $filename = "",$returnName)
    {
        if (empty($filename)) {
            header("content-type: image/png");
        }
        $imageDefault = array(
            'left' => 0,
            'right' => 0,
            'bottom' => 0,
            'width' => 100,
            'height' => 100,
            'opacity' => 100
        );

        $textDefault = array(
            'text' => '',
            'left' => 0,
            'fontSize' => 32, // 字号
            'fontColor' => '255,255,255', // 字体颜色
            'angle' => 0,
        );

        $background = $config['background']; // 海报最底层的背景

        // 背景方法
        $backgroundInfo = getimagesize($background);
        $backgroundFun = 'imagecreatefrom' . image_type_to_extension($backgroundInfo[2], false);
        $background = $backgroundFun($background);
        $backgroundWidth = imagesx($background); // 背景宽度
        $backgroundHeight = imagesy($background); // 背景高度
        $imageRes = imagecreatetruecolor($backgroundWidth, $backgroundHeight);
        $color = imagecolorallocate($imageRes, 0, 0, 0);
        imagefill($imageRes, 0, 0, $color);

        imagecopyresampled(
            $imageRes,
            $background,
            0,
            0,
            0,
            0,
            imagesx($background),
            imagesy($background),
            imagesx($background),
            imagesy($background)
        );

        // 处理图片
        $qrcodeConfig = null;
        if (!empty($config['image'])) {
            foreach ($config['image'] as $key => $val) {
                $val = array_merge($imageDefault, $val);
                $info = getimagesize($val['url']);
                $function = 'imagecreatefrom' . image_type_to_extension($info[2], false);
                if ($val['stream']) {
                    // 如果传的是字符串图像流
                    $info = getimagesizefromstring($val['url']);
                    $function = 'imagecreatefromstring';
                }
                $res = $function($val['url']);
                $resWidth = $info[0];
                $resHeight = $info[1];

                // 如果需要将头像转换为圆形
                if (isset($val['isAvatar']) && $val['isAvatar']) {
                    $canvas = $this->createRoundImage($res, $val['width'], $val['height']);
                    $resWidth = imagesx($canvas);
                    $resHeight = imagesy($canvas);
                }else{
                    // 建立画板，缩放图片至指定尺寸
                    $canvas = imagecreatetruecolor($val['width'], $val['height']);
                    imagesavealpha($canvas, true);
                    $transColour = imagecolorallocatealpha($canvas, 0, 0, 0, 127);
                    imagefill($canvas, 0, 0, $transColour);

                    imagecopyresampled(
                        $canvas,
                        $res,
                        0,
                        0,
                        0,
                        0,
                        $val['width'],
                        $val['height'],
                        $resWidth,
                        $resHeight
                    );
                }

                $val['left'] = $val['left'] < 0 ? $backgroundWidth - abs($val['left']) - $val['width'] : $val['left'];
                $val['top'] = $val['top'] < 0 ? $backgroundHeight - abs($val['top']) - $val['height'] : $val['top'];

                // 放置图像
                imagecopyresampled(
                    $imageRes,
                    $canvas,
                    $val['left'],
                    $val['top'],
                    0,
                    0,
                    $val['width'],
                    $val['height'],
                    $val['width'],
                    $val['height']
                );

                if (isset($val['isQRCode']) && $val['isQRCode']) {
                    $qrcodeConfig = $val;
                }
            }
        }

        // 处理文字
        if (!empty($config['text'])) {
            foreach ($config['text'] as $key => $val) {
                $val = array_merge($textDefault, $val);
                list($R, $G, $B) = explode(',', $val['fontColor']);
                $fontColor = imagecolorallocate($imageRes, $R, $G, $B);

                if (isset($val['centerToQRCode']) && $val['centerToQRCode'] && $qrcodeConfig) {
                    $textBox = imagettfbbox($val['fontSize'], $val['angle'], $val['fontPath'], $val['text']);
                    $textWidth = $textBox[2] - $textBox[0];
                    $val['left'] = $qrcodeConfig['left'] + ($qrcodeConfig['width'] - $textWidth) / 2;
                } else {
                    $val['left'] = $val['left'] < 0 ? $backgroundWidth - abs($val['left']) : $val['left'];
                }

                $val['top'] = $val['top'] < 0 ? $backgroundHeight - abs($val['top']) : $val['top'];
                imagettftext(
                    $imageRes,
                    $val['fontSize'],
                    $val['angle'],
                    $val['left'],
                    $val['top'],
                    $fontColor,
                    $val['fontPath'],
                    $val['text']
                );
            }
        }

        // 生成图片
        if (!empty($filename)) {
            $res = imagejpeg($imageRes, $filename, 90); // 保存到本地
            imagedestroy($imageRes);
            if (!$res) return false;
            return $returnName;
        } else {
            imagejpeg($imageRes); // 在浏览器上显示
            imagedestroy($imageRes);
        }
    }
    /*
     * 生成带有图像，昵称和二维码的海报
     * @path /api/ad/poster
     * $erCode小程序二维码
     *
    */
    public function poster($erCode,$avatar,$rootPath,$username)
    {
        $code = $erCode;
        //示例2：生成带有图像，昵称和二维码的海报
        $config = array(
            'text' => array(
                array(
                    'text' => $username,
                    'left' => 330,
                    'top' => 610,
                    'fontPath' => $rootPath.'/assets/ttf/fdbsjw.ttf',     //字体文件
                    'fontSize' => 25,             //字号
                    'fontColor' => '23,23,23',       //字体颜色
                    'angle' => 0,
                    'centerToQRCode' => true // 根据二维码居中
                ),
                array(
                    'text' => '扫描或长按识别二维码进行注册',
                    'left' => 205,
                    'top' => -105,
                    'fontSize' => 18,
                    'fontColor' => '23,23,23',
                    'fontPath' => $rootPath.'/assets/ttf/fdbsjw.ttf', //字体文件
                ),
            ),
            'image' => array(
                array(
                    'url' => $code,       //图片资源路径
                    'left' => 210,
                    'top' => -142,
                    'stream' => 0,             //图片资源是否是字符串图像流
                    'right' => 0,
                    'bottom' => 0,
                    'width' => 330,
                    'height' => 330,
                    'isQRCode' => true,
                    'opacity' => 100
                ),
                array(
                    'url' => $avatar,
                    'left' => 330,
                    'top' => 493,
                    'right' => 0,
                    'stream' => 0,
                    'bottom' => 0,
                    'width' => 85,
                    'height' => 85,
                    'isAvatar' => true, // 标记为头像图像
                    'opacity' => 100,
                ),
            ),
            'background' => $rootPath.'/share_bg.png',
        );
        $filename = $rootPath.'/xcx_user_qrcode/' . time() . '.png';
        $returnName = '/xcx_user_qrcode/' . time() . '.png';

        $res = $this->createPoster($config, $filename,$returnName);
        return $res;
    }

    // 生成的图片为圆形突变
    public function posters()
    {
        // $srcFile = './file/storage/image/wx.jpg';
        // $img_path = './file/storage/image/wx_y2.jpg';
        // $ino = $this->roundImg($srcFile,$img_path,0);
        // dump($ino);die();
        $imgpath = "./file/storage/image/wx.jpg";
        $imgg = $this->radius_img($imgpath, 300);
        $res = imagejpeg($imgg, './file/storage/image/wx_yy.jpg', 100);
        dump($res);
        die();
    }

    /**
     * 图片圆角处理函数
     * @param source $srcFile 本地图片路径
     * @param source $img_path 保存路径
     * @param string $size 圆角尺寸   0 则为圆形图
     */
    public function roundImg($srcFile, $img_path, $size = 0)
    {
        // Get image extension
        $ext = pathinfo($srcFile);

        // Get image info
        $data = getimagesize($srcFile);

        // Load the source image
        switch ($data[2]) {
            case IMAGETYPE_GIF:
                $srcImg = imagecreatefromgif($srcFile);
                break;
            case IMAGETYPE_JPEG:
                $srcImg = imagecreatefromjpeg($srcFile);
                break;
            case IMAGETYPE_PNG:
                $srcImg = imagecreatefrompng($srcFile);
                break;
            case IMAGETYPE_WBMP:
                $srcImg = imagecreatefromwbmp($srcFile);
                break;
            default:
                return false;
        }

        // Get image dimensions
        $w = imagesx($srcImg);
        $h = imagesy($srcImg);

        // Determine the size of the canvas
        $side = min($w, $h);
        if ($size > 0) {
            $side = $size;
        }

        // Create a new square canvas with transparency
        $img = imagecreatetruecolor($side, $side);
        imagesavealpha($img, true);
        $transparent = imagecolorallocatealpha($img, 0, 0, 0, 127);
        imagefill($img, 0, 0, $transparent);

        // Calculate center and radius
        $radius = $side / 2;
        $centerX = $radius;
        $centerY = $radius;

        // Resize and center the original image
        $srcX = ($w - $side) / 2;
        $srcY = ($h - $side) / 2;
        imagecopyresampled($img, $srcImg, 0, 0, $srcX, $srcY, $side, $side, $side, $side);

        // Apply the circular mask
        $mask = imagecreatetruecolor($side, $side);
        imagesavealpha($mask, true);
        $transparent = imagecolorallocatealpha($mask, 0, 0, 0, 127);
        imagefill($mask, 0, 0, $transparent);
        $maskColor = imagecolorallocate($mask, 255, 255, 255);

        // Create circular mask
        imagefilledellipse($mask, $centerX, $centerY, $side, $side, $maskColor);
        imagecolortransparent($mask, $maskColor);

        // Combine images
        imagecopymerge($img, $mask, 0, 0, 0, 0, $side, $side, 100);

        // Save the output image
        switch ($data[2]) {
            case IMAGETYPE_GIF:
                imagegif($img, $img_path);
                break;
            case IMAGETYPE_JPEG:
                imagejpeg($img, $img_path, 100);
                break;
            case IMAGETYPE_PNG:
                imagepng($img, $img_path);
                break;
            case IMAGETYPE_WBMP:
                imagewbmp($img, $img_path);
                break;
        }

        // Clean up
        imagedestroy($srcImg);
        imagedestroy($img);
        imagedestroy($mask);

        return $img_path;
    }

    public function radius_img($imgpath = '', $radius = 15)
    {
        $ext = pathinfo($imgpath);
        $src_img = null;
        $wh = getimagesize($imgpath);
        switch ($wh[2]) {
            case '1':
                $src_img = imagecreatefromjpeg($imgpath);
                break;
            case '2':
                $src_img = imagecreatefromjpeg($imgpath);
                break;
            case '3':
                $src_img = imagecreatefrompng($imgpath);
                break;
        }
        $w = $wh[0];
        $h = $wh[1];
        $radius = $radius == 0 ? (min($w, $h) / 2) : $radius;
        $img = imagecreatetruecolor($w, $h);
        //这一句一定要有
        imagesavealpha($img, true);
        //拾取一个完全透明的颜色,最后一个参数127为全透明
        $bg = imagecolorallocatealpha($img, 255, 255, 255, 127);
        imagefill($img, 0, 0, $bg);
        $r = $radius; //圆 角半径
        for ($x = 0; $x < $w; $x++) {
            for ($y = 0; $y < $h; $y++) {
                $rgbColor = imagecolorat($src_img, $x, $y);
                if (($x >= $radius && $x <= ($w - $radius)) || ($y >= $radius && $y <= ($h - $radius))) {
                    //不在四角的范围内,直接画
                    imagesetpixel($img, $x, $y, $rgbColor);
                } else {
                    //在四角的范围内选择画
                    //上左
                    $y_x = $r; //圆心X坐标
                    $y_y = $r; //圆心Y坐标
                    if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) {
                        imagesetpixel($img, $x, $y, $rgbColor);
                    }
                    //上右
                    $y_x = $w - $r; //圆心X坐标
                    $y_y = $r; //圆心Y坐标
                    if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) {
                        imagesetpixel($img, $x, $y, $rgbColor);
                    }
                    //下左
                    $y_x = $r; //圆心X坐标
                    $y_y = $h - $r; //圆心Y坐标
                    if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) {
                        imagesetpixel($img, $x, $y, $rgbColor);
                    }
                    //下右
                    $y_x = $w - $r; //圆心X坐标
                    $y_y = $h - $r; //圆心Y坐标
                    if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) {
                        imagesetpixel($img, $x, $y, $rgbColor);
                    }
                }
            }
        }
        return $img;
    }

    // 生成圆图
    public function createRoundImage($srcImgOld,$width,$height)
    {
        $srcImg = imagecreatetruecolor(imagesx($srcImgOld), imagesy($srcImgOld));
        imagecopy($srcImg, $srcImgOld, 0, 0, 0, 0, imagesx($srcImgOld), imagesy($srcImgOld));

        // header('Content-Type: image/png');
        $imgWidth = imagesx($srcImg);
        $imgHeight = imagesy($srcImg);
        $minSize = min($imgWidth, $imgHeight);
        $srcImg = imagecrop($srcImg, ['x' => ($imgWidth - $minSize) / 2, 'y' => ($imgHeight - $minSize) / 2, 'width' => $minSize, 'height' => $minSize]);

        $newImg = imagecreatetruecolor($minSize, $minSize);
        imagesavealpha($newImg, true);
        $transColour = imagecolorallocatealpha($newImg, 0, 0, 0, 127);
        imagefill($newImg, 0, 0, $transColour);

        $r = $minSize / 2; // 圆半径
        for ($x = 0; $x < $minSize; $x++) {
            for ($y = 0; $y < $minSize; $y++) {
                $srcX = round($x * $minSize / $minSize);
                $srcY = round($y * $minSize / $minSize);
                if ((($x - $r) * ($x - $r) + ($y - $r) * ($y - $r)) < ($r * $r)) {
                    $rgbColor = imagecolorat($srcImg, $srcX, $srcY);
                    imagesetpixel($newImg, $x, $y, $rgbColor);
                }
            }
        }

        // 创建一个新图片，用于保存缩略图
        $imageResized = imagecreatetruecolor($width, $height);

        // 对于PNG，我们还需要处理透明度
        imagealphablending($imageResized, false);
        imagesavealpha($imageResized, true);
        // 复制并调整图片大小
        imagecopyresampled($imageResized, $newImg, 0, 0, 0, 0, $width, $height, $minSize, $minSize);
        return $imageResized;
    }
}
